﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;

namespace IcicleFramework.Components.Metadata
{
    public class MetadataComponent : BaseComponent, IMetadataComponent
    {
        protected Dictionary<string, object> Metadata { get; set; }

        public override void Update(GameTime gameTime)
        { }

        public MetadataComponent()
        {
            Metadata = new Dictionary<string, object>();
        }

        public override IBaseComponent DeepClone()
        {
            MetadataComponent component = new MetadataComponent();
            Dictionary<string, object> metadata = new Dictionary<string, object>();

            foreach (string key in Metadata.Keys)
                metadata.Add(key, Metadata[key]);

            component.Metadata = metadata;

            return component;
        }

        public void AddMetadata(string key, object value)
        {
            if (!Metadata.ContainsKey(key))
                Metadata.Add(key, value);
        }

        public void ChangeValue(string key, object value)
        {
            if (Metadata.ContainsKey(key))
                Metadata[key] = value;
        }

        public bool HasMetadata(string key)
        {
            return Metadata.ContainsKey(key);
        }

        public object GetMetadata(string key)
        {
            if (Metadata.ContainsKey(key))
                return Metadata[key];

            return null;
        }

        public override void Deserialize(XElement element)
        {
            List<XElement> metadataElems = element.Elements("metadata").ToList();

            for (int i = 0; i < metadataElems.Count; i++)
            {
                XAttribute nameAttrib = metadataElems[i].Attribute("name");
                if (nameAttrib != null)
                {
                    Metadata.Add(nameAttrib.Value, null);

                    XAttribute valueAttrib = metadataElems[i].Attribute("value");
                    if (valueAttrib != null)
                        Metadata[nameAttrib.Value] = valueAttrib.Value;
                }
            }
        }

        
    }
}
